package com.base.cn.platform.os.controller.course.cou.packageCou;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.CourseCondition;
import com.base.cn.platform.os.entity.course.cou.packageCou.PackageCourse;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.packageCou.PackageCourseBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 套餐与课程关联的Controller
 *
 * @author s.li
 * @create 2018-05-02-15:28
 */
@RestController
@RequestMapping("/course")
public class PackageCourseController extends BaseController {

    @Autowired
    private PackageCourseBiz packageCourseBiz;
    @Autowired
    private CourseBiz courseBiz;

    /**
     * 创建阶段
     * @param packageId 套餐ID
     * @param stageContext 阶段内容
     */
    @RequestMapping("/createStage")
    public Map<String,Object> createStage(@RequestParam("packageId") BigDecimal packageId,
                                          @RequestParam("stageContext") String stageContext){

        if(StringUtils.isEmpty(stageContext)){
            return ResultUtil.ERROR("请填写阶段描述信息");
        }
        Course course = courseBiz.findCourseById(false,packageId,false,false,false);
        if(ObjectUtils.isEmpty(course)){
            return ResultUtil.ERROR("套餐课程不存在，操作失败");
        }
        if(course.getStatus().intValue()!=0){
            return ResultUtil.ERROR("套餐状态错误，创建阶段失败");
        }
        packageCourseBiz.createStage(packageId,stageContext);
        return ResultUtil.SUCCESS("阶段创建成功");
    }

    /**
     * 保存套餐与课程的关联
     * @param parentId 父ID（阶段ID）
     * @param packageId 套餐ID
     * @param courseIds 添加的课程ID串
     */
    @RequestMapping("/savePackageCourse")
    public Map<String,Object> savePackageCourse(@RequestParam(value = "parentId",required = false,defaultValue = "0") BigDecimal parentId,
                                                @RequestParam("packageId") BigDecimal packageId,
                                                @RequestParam("courseIds") String courseIds){
        if(StringUtils.isEmpty(courseIds)){
            return ResultUtil.ERROR("套餐关联的课程数据错误");
        }
        Course course = courseBiz.findCourseById(false,packageId,false,false,false);
        if(ObjectUtils.isNotEmpty(course)){
            if(course.getStatus().intValue()!=0){
                return ResultUtil.ERROR("当前状态的套餐不可添加课程");
            }
        }else{
            return ResultUtil.ERROR("套餐课程的不存在，操作失败");
        }
        //最大拥有课程量
        int courseNum = course.getCourseNum().intValue();
        int _num = 0;
        //套餐原来包含的课程
        List<PackageCourse> packageCourseList = packageCourseBiz.findPackageCourseByPackageId(packageId,false);
        if(ObjectUtils.isNotEmpty(packageCourseList)){
            //通过是否是是课程类型为条件分组，排除阶段类型的记录
            Map<Boolean,List<PackageCourse>> map = packageCourseList.stream().collect(Collectors.groupingBy(e->e.getPackageType().intValue()==1));
            List<PackageCourse> list = map.get(true);
            if(ObjectUtils.isNotEmpty(list)){
                _num = list.size();
            }
            if( _num >= courseNum){
                return ResultUtil.ERROR("套餐已包含最大限制"+courseNum+"个课程,不可再添加");
            }
        }
        CourseCondition condition = new CourseCondition();
        condition.setIds(courseIds);
        //要新关联的课程数据
        List<Course> courseList = courseBiz.findCourseList(condition,false,false,false);
        if(ObjectUtils.isEmpty(courseList)){
            return ResultUtil.ERROR("套餐要关联的课程不存在");
        }
        //要添加的数据列表
        List<PackageCourse> packageCourses = new ArrayList<>();
        //把要关联的课程列表转成Map
        Map<BigDecimal,Course> courseMaps = null;
        //如果原来有添加过课程
        if(ObjectUtils.isNotEmpty(packageCourseList)){
            //把要关联的课程列表转成Map
            Map<BigDecimal,Course> _courseMaps = courseList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
            packageCourseList.forEach(e->{
                Course _course = _courseMaps.get(e.getCourseId());
                if(ObjectUtils.isNotEmpty(_course)){
                    _courseMaps.remove(e.getCourseId());//如果课程已存在，则删除
                }
            });
            courseMaps = _courseMaps;
        }else{//如果套餐没有设置过课程
            courseMaps = courseList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
        }
        if(ObjectUtils.isNotEmpty(courseMaps)){
            courseMaps.forEach((k,v)->{
                PackageCourse packageCourse = new PackageCourse();
                packageCourse.setPackageType(1);
                packageCourse.setPackageId(packageId);
                packageCourse.setCourseId(v.getId());
                packageCourse.setPrice(v.getRealPrice());
                packageCourse.setCourseTypeKey(v.getCourseTypeKey());
                packageCourse.setRequired(2);
                packageCourse.setParentId(parentId);
                packageCourses.add(packageCourse);
            });
        }
        if(ObjectUtils.isNotEmpty(packageCourses)){
            if(packageCourses.size()+_num > courseNum){
                return ResultUtil.ERROR("套餐最多可设置"+courseNum+"个课程");
            }
            packageCourseBiz.savePackageCourse(packageCourses,course,packageId);
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 删除套餐与课程的关联数据
     * @param packageId 套餐ID
     * @param ids 记录ID串
     */
    @RequestMapping("/deletePackageCourse")
    public Map<String,Object> deletePackageCourse(@RequestParam("packageId") BigDecimal packageId,
                                                  @RequestParam("ids") String ids){
        Course course = courseBiz.findCourseById(false,packageId,false,false,false);
        if(ObjectUtils.isNotEmpty(course)){
            if(course.getStatus().intValue()!=0){
                return ResultUtil.ERROR("当前状态的套餐不可删除套餐下的课程关联");
            }
        }
        packageCourseBiz.deletePackageCourse(ids,course,packageId);
        return ResultUtil.SUCCESS("删除成功");
    }

    /**
     * 修改套餐与课程关联的价格
     * @param id 记录ID
     * @param price 新的价格
     */
    @RequestMapping("/updatePackageCoursePrice")
    public Map<String,Object> updatePackageCoursePrice(@RequestParam("id") BigDecimal id,
                                                       @RequestParam("price") Double price){
        packageCourseBiz.updatePackageCoursePrice(id,price);
        return ResultUtil.SUCCESS("课程价格修改成功");
    }

    /**
     * 修改套餐与课程关联的排序
     * @param id
     * @param sort
     * @return
     */
    @RequestMapping("/updatePackageCourseSort")
    public Map<String,Object> updatePackageCourseSort(@RequestParam("id") BigDecimal id,
                                                      @RequestParam("sort") Integer sort){
        packageCourseBiz.updatePackageCourseSort(id,sort);
        return ResultUtil.SUCCESS("排序修改成功");
    }

    /**
     * 修改套餐与课程关联的必须状态
     * @param id 记录ID
     * @param required 1.必选 2.非必选
     */
    @RequestMapping("/updatePackageCourseRequired")
    public Map<String,Object> updatePackageCourseRequired(@RequestParam("id") BigDecimal id,
                                                          @RequestParam("required") int required){
        packageCourseBiz.updatePackageCourseRequired(id,required);
        return ResultUtil.SUCCESS();
    }

    /**
     * 查询套餐下关联的课程数据列表
     * @param packageId 套餐ID
     * @param setCourseData 是否设置课程，true设置，false不设置
     * @return List<PackageCourse>
     */
    @RequestMapping("/findPackageCourseByPackageId")
    public List<PackageCourse> findPackageCourseByPackageId(@RequestParam("packageId") BigDecimal packageId,
                                                            @RequestParam("setCourseData") boolean setCourseData){
        return packageCourseBiz.findPackageCourseByPackageId(packageId,setCourseData);
    }

    /**
     * 查询套餐下的课程目录
     * @param userId 用户ID
     * @param packageId 套餐ID
     * @param setCourseData  是否设置课程数据
     * @return Map<Integer,List<PackageCourse>>
     */
    @RequestMapping("/findUserLayeredPackageCourseByPackageId")
    public Map<Integer,List<PackageCourse>> findUserLayeredPackageCourseByPackageId(@RequestParam("userId") BigDecimal userId,
                                                                                    @RequestParam("packageId") BigDecimal packageId,
                                                                                    @RequestParam("setCourseData") boolean setCourseData){
        return packageCourseBiz.findUserLayeredPackageCourseByPackageId(userId,packageId,setCourseData);
    }

    /**
     * 查询套餐下关联的课程数据列表(分层)
     * @param packageId 套餐ID
     * @param setCourseData 是否设置课程，true设置，false不设置
     * @return  Map<Integer,List<PackageCourse>>
     */
    @RequestMapping("/findLayeredPackageCourseByPackageId")
    public  Map<Integer,List<PackageCourse>> findLayeredPackageCourseByPackageId(@RequestParam("packageId") BigDecimal packageId,
                                                                   @RequestParam("setCourseData") boolean setCourseData){
        return packageCourseBiz.findLayeredPackageCourseByPackageId(packageId,setCourseData);
    }
}
